import { defineStore } from "pinia";

import { ref } from "vue";
import { LoginUserVO, UserControllerService } from "@/api";
import ACCESS_ENUM from "@/access/ACCESS_ENUM";

export const useUserStore = defineStore(
  "user",
  () => {
    const userInfo = ref<LoginUserVO>({
      username: "暂未登录" + new Date().getTime(),
      role: ACCESS_ENUM.NO_LOGIN,
    });
    const token = ref<string>("");
    const getLoginUser = async () => {
      //接口获取数据
      const res = await UserControllerService.getLoginUserUsingGet();
      if (res.code === 0) {
        userInfo.value = res?.data ?? {};
      }
      return userInfo.value;
    };
    const removeLoginUser = async () => {
      const res = await UserControllerService.userLogoutUsingPost();
      if (res.code === 0) {
        userInfo.value = {
          username: "暂未登录" + new Date().getTime(),
          role: ACCESS_ENUM.NO_LOGIN,
        };
      }
    };
    return { userInfo, token, getLoginUser, removeLoginUser };
  },
  {
    persist: true,
  }
);
